import random
import time

import logo.Mlog
from dataTemp.prop import Prop
from dataTemp.task import Task
from event import event
from event.keypresser import KeyPressManager
from logo import Mlog
from process.yg import YG
from tool.vector import Vector


class Player:
    def __init__(self):
        self.name = ""
        self.job = ""
        self.roles = []
        # 这个是实时赋值的
        self.temp_pot = None
        self.position = None
        self.wh = None
        # 任务进度
        self.__rate = 0
        self.tasks = []
        # 任务是否完成
        self.is_complete = False
        # 是否开启技能
        self.open_Skill = False
        # 是否释放技能
        self.is_releaseSkill = False
        self.buff_ok = False
        # 46
        self.move_offset_y = 40
        self.move_offset_x = 20
        # 是否已经释放过觉醒技能
        self.is_final_skill = False
        self.enemies = []
        #
        self.key_pro = KeyPressManager()
        self.yg = YG()

    # 默认是面对右边
    direction: str = "D"
    ems: [Prop] = []
    no_Body_times: int = 0
    def releaseSkill(self,cy, enems: [Prop]):
        if self.temp_pot is None or len(enems) <= 0:
            # Mlog.logger.debug(f"落单模式攻击敌人1={self.temp_pot}")
            self.releaseSkill2()
            self.no_Body_times += 1
            if self.no_Body_times >= 20:
                self.key_pro.clear_key()
                self.random_move_y()
                Mlog.logger.error(f"落单模式没有找到 子集 和 敌人 自由移动一下")
                self.no_Body_times = 0
                # cy.sm.transition_to("et")
            return
        # 只要敌人再xy轴之内，就可以释放技能
        left_count, right_count = self.count_enemies_on_each_side(enems)
        if len(left_count) > len(right_count) and not self.direction == "A":
            self.direction = "A"
            logo.Mlog.logger.warn("敌人在左边")
            # 找一名敌人判断xy轴是否可以释放技能
            self.ems = left_count
            # self.set_y(self.ems[0].pot.y)
            # self.yg.left_move()
            self.left_move(0.1)
        elif len(left_count) < len(right_count) and not self.direction == "D":
            self.direction = "D"
            logo.Mlog.logger.warn("敌人在右边")
            self.ems = right_count
            # self.set_y(self.ems[0].pot.y)
            self.right_move(0.1)
            # self.yg.right_move()
        # 找到x距离最近的
        if len(self.ems) <= 0:
            self.releaseSkill2()
            self.no_Body_times += 1
            if self.no_Body_times >= 25:
                self.key_pro.clear_key()
                self.random_move_y()
                Mlog.logger.error(f"落单模式没有找到敌人 自由移动一下")
                self.no_Body_times = 0
                # cy.sm.transition_to("et")
            return
        # p = min(self.ems, key=lambda e: Vector.distance(e.pot, self.position))
        # self.set_y(p.pot.y)
        p = min(self.ems, key=lambda e: Vector.distance(e.getPot(), self.position))
        if not self.is_absolute_difference_within_range(p.x, self.position.x, self.wh.y*2) and not self.is_absolute_difference_within_range(p.y, self.position.y, self.wh.y-self.wh.y/3):
            self.key_pro.clear_key()
            Mlog.logger.warning(f"攻击敌人距离不够需要移动 {len(self.ems)}")
            self.find_way(p.getPot(), 0.1)
            time.sleep(0.6)
            # if self.set_y(p.pot.y):
        else:
            self.releaseSkill2()
            # Mlog.logger.debug(f"攻击敌人 {len(self.ems)}")
        pass

    # 检测不到自己，但是能检测到敌人时
    skill_times: int = 0

    def releaseSkill2(self):
        if self.skill_times < 2:
            self.skill()
        elif self.skill_times >= 2:
            self.aaa()
            self.skill_times = 0
        # logo.Mlog.logger.warning(f"落单模式，自由释放技能中 {self.skill_times}")
        self.skill_times += 1
        pass

    def skill(self):
        self.key_pro.set_key("E", 0)

    def aaa(self):
        self.key_pro.set_key("X", 0.6)

    # 释放觉醒技能
    final_skill_times: int = 0

    def final_skill(self):
        self.final_skill_times += 1
        if self.final_skill_times < 3:
            # self.key_pro.stop_key()
            # self.key_pro.press_key_in_background("R", 0)
            self.key_pro.set_key("R", 0.3)
            logo.Mlog.logger.warning(f"释放觉醒 {self.is_final_skill}")
            # self.is_final_skill = True
        pass

    # 获取角色的底部坐标，默认在中心点
    def get_down_pot(self, y_offset: float = 0) -> Vector:
        if self.position is None: return None
        y = self.position.y + self.wh.y / 2 - y_offset
        x = self.position.x + self.wh.x / 2
        return Vector(x, y)

    # 切换房间时角色要做的事
    def cut_room(self):
        pass

    # 通关后的一些重置操作
    def reset_player(self):
        self.buff_ok = False
        self.is_final_skill = False
        self.final_skill_times = 0
        logo.Mlog.logger.warning(f"player 重置")

    def add_buff(self):
        if not self.buff_ok:
            logo.Mlog.logger.warning(f"进图上 buff {self.buff_ok}")
            # 按下Ctrl和C键
            # pyautogui.hotkey('C', 'V')
            self.key_pro.set_key("C", 0.3)
            time.sleep(0.1)
            self.key_pro.set_key("v", 0.3)
            self.buff_ok = True

    # 判断那一边的敌人多
    def count_enemies_on_each_side(self, enems: [Prop]):
        left_count: [Prop] = []
        right_count: [Prop] = []
        for e in enems:
            if e.x < self.position.x:
                left_count.append(e)
            else:
                right_count.append(e)
        return left_count, right_count

    # 左右对齐
    def set_x(self, x: float, is_enemy: bool = True, duration: float = 0.1) -> bool:
        if is_enemy:
            offset = 350
        else:
            offset = 30
        if not self.is_absolute_difference_within_range(self.position.x, x, offset):
            # logo.Mlog.logger.debug(f"x轴距离={self.position.x - x:},范围350")
            if self.position.x > x:
                # 向上移动一下上下对敌人80像素开始释放技能
                self.left_move(duration)
                return False
            elif self.position.x < x:
                # 向上移动一下上下对敌人80像素开始释放技能
                self.right_move(duration)
                return False
        return True

    # 上下对齐
    def set_y(self, y: float, is_enemy: bool = True, duration: float = 0.1) -> bool:
        if is_enemy:
            offset = 250
        else:
            offset = 60
        if not self.is_absolute_difference_within_range(self.position.y, y, offset):
            logo.Mlog.logger.debug(
                f"self.y={self.position.y}，d敌人。y={y} ,y轴距离={self.position.y - y:},范围={offset}")
            if self.position.y > y:
                # 向上移动一下上下对敌人80像素开始释放技能
                self.up_move(duration)
                return False
            elif self.position.y < y:
                # 向上移动一下上下对敌人80像素开始释放技能
                self.down_move(duration)
                return False
        return True

    # 向这y轴方向一直移动
    def move_direction(self, duration: float = 0.1):
        self.yg.move_direction(duration)
        # event.press_key_for_duration(self.direction, duration)

    # 向这y轴方向一直移动
    # def look_enemy(self, pot: Vector, duration: float = 0.1):
    #     self.yg.move(self.position,pot ,duration)

    # 向这y轴方向一直移动
    def find_way(self, pot: Vector, duration: float = 0.1):
        if self.get_down_pot() is None: return
        self.yg.move(self.get_down_pot(), pot, duration)

    # 同步移动
    def up_move(self, duration: float = 0.1):
        logo.Mlog.logger.warning(f"同步向上移x={self.yg.pot.x - self.yg.r},y={self.yg.pot.y}")
        self.key_pro.clear_key()
        self.yg.up_move(duration)
        time.sleep(0.5)
        # event.mouse_hold(self.yg.pot.x, self.yg.pot.y - self.yg.r, duration)

    def down_move(self, duration: float = 0.1):
        logo.Mlog.logger.warning(f"同步向下移")
        self.key_pro.clear_key()
        self.yg.down_move(duration)
        time.sleep(0.5)
        # event.mouse_hold(self.yg.pot.x, self.yg.pot.y + self.yg.r, duration)

    def left_move(self, duration: float = 0.1):
        self.key_pro.clear_key()
        logo.Mlog.logger.warning(f"同步向左移")
        self.yg.left_move(duration)
        time.sleep(0.5)
        # event.mouse_hold(self.yg.pot.x - self.yg.r, self.yg.pot.y, duration)

    def right_move(self, duration: float = 0.1):
        self.key_pro.clear_key()
        logo.Mlog.logger.warning(f"同步向右移")
        self.yg.right_move(duration)
        time.sleep(0.5)
        # event.mouse_hold(self.yg.pot.x + self.yg.r, self.yg.pot.y, duration)

    # 通关后随意走动一下判断是否还有材料
    def random_move(self):
        random_int = random.randint(0, 3)
        tm = random.uniform(0, 0.5)
        if random_int == 0:
            self.up_move(tm)
        if random_int == 1:
            self.down_move(tm)
        if random_int == 2:
            self.left_move(tm)
        if random_int == 3:
            self.right_move(tm)

    def random_move_y(self):
        random_int = random.randint(0, 1)
        tm = random.uniform(0, 0.2)
        if random_int == 0:
            self.up_move(tm)
        if random_int == 1:
            self.down_move(tm)
    def is_absolute_difference_within_range(self, num1: float, num2: float, range_value: float) -> bool:
        abs_diff = abs(num1 - num2)
        # logo.Mlog.logger.debug(f"检测2点之间的差距{abs_diff}")
        return abs_diff <= range_value

    # def addRole(self,roles:[Role]):
